package interceptor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 拦截器
 * 在链中节点自己可以打断 可以继续执行
 * @description:
 * @author: wangxun
 * @createDate: 2022/1/18
 * @version: 1.0
 */
public class Interceptor02 {
    /**
     * 拦截器
     */
    interface  WxInterceptor{
        /**
         * 拦截方法
         */
        Object plugin(Object target,WxInterceptorChain wxInterceptorChain);
    }

    static class WxInterceptorA implements  WxInterceptor{

        @Override
        public Object plugin(Object target,WxInterceptorChain wxInterceptorChain) {
            System.out.println("拦截器A");
            wxInterceptorChain.exe(target);
            return target;
        }
    }
    static class WxInterceptorB implements  WxInterceptor{

        @Override
        public Object plugin(Object target,WxInterceptorChain wxInterceptorChain) {
            System.out.println("拦截器B");
            return target;
        }
    }
    static class WxInterceptorC implements  WxInterceptor{

        @Override
        public Object plugin(Object target,WxInterceptorChain wxInterceptorChain) {
            System.out.println("拦截器C");
            return target;
        }
    }

    static class WxInterceptorChain{
        private List<WxInterceptor> interceptors = new ArrayList<>();
        Iterator<WxInterceptor> iterator ;
        // 添加方法
        public void addInterceptor(WxInterceptor wxInterceptor){
            interceptors.add(wxInterceptor);
        }

        public void exe(Object target){
            if(iterator == null){
                iterator = interceptors.iterator();
            }

            if(iterator.hasNext()){ // 这里没有用循环，直接找到第一个节点，将链交给它，让节点自己决定是否继续执行 将迭代器做成一个全局变量

                WxInterceptor next = iterator.next();
                next.plugin(target, this);
            }
        }


    }

    public static void main(String[] args) {
        WxInterceptorChain wxInterceptorChain = new WxInterceptorChain();
        wxInterceptorChain.addInterceptor(new WxInterceptorA());
        wxInterceptorChain.addInterceptor(new WxInterceptorB());
        wxInterceptorChain.addInterceptor(new WxInterceptorC());

        wxInterceptorChain.exe(new Object());

    }


}
